<template>
  <div class="frame-container">
    <div
      v-if="!tips"
      class="container"
    >
      <van-cell-group>
        <single-picker
          id="category_id"
          label="分类"
          :value="formData.category_id"
          :data="categorys"
          required
          content-column="name"
          value-column="id"
          placeholder="请选择分类"
          :error="!!errorMessage.category_id"
          @change="onCheckedCategory"
        />
      </van-cell-group>
      <van-cell-group custom-class="textarea-cell">
        <van-field
          id="title"
          :value="formData.title"
          confirm-type="next"
          required
          label="标题"
          placeholder="请输入标题内容，不可超过50字"
          :maxlength="50"
          :error="!!errorMessage.title"
          @change="onChangeInput"
        />
      </van-cell-group>
      <van-cell-group custom-class="textarea-cell">
        <van-field
          id="content"
          :value="formData.content"
          type="textarea"
          required
          label="内容"
          placeholder="请输入内容描述，不可超过1000字"
          :maxlength="1000"
          :autosize="textareaOption"
          :error="!!errorMessage.content"
          :error-message="errorMessage.content"
          @change="onChangeInput"
        />
      </van-cell-group>
      <van-cell-group>
        <van-cell
          title="图片"
          value="可上传多张图片内容"
        />
        <div class="images-upload">
          <van-uploader
            name="images"
            :file-list="imageList"
            :max-count="10"
            multiple
            image-fit="aspectFill"
            @afterRead="onAfterReadFiles"
            @delete="onDeleteImage"
          />
        </div>
      </van-cell-group>
      <van-cell-group>
        <van-cell
          title="附件"
          title-width="80px"
          custom-class="file-upload"
        >
          <van-uploader
            name="attach"
            accept="file"
            :file-list="attachs"
            :max-count="1"
            @afterRead="onAfterRead"
            @delete="onDeleteAttach"
          >
            <van-button
              icon="plus"
              type="primary"
              size="small"
            >上传文件</van-button>
          </van-uploader>
        </van-cell>
      </van-cell-group>
      <div class="form-action">
        <van-button
          type="info"
          round
          @click="onSubmit"
        >发布</van-button>
      </div>
    </div>
    <van-empty
      v-else
      :description="tips.description"
      :image="tips.image"
    >
      <van-button
        round
        :type="button.type"
        class="bottom-button"
        v-for="(button,index) in tips.buttons"
        :key="index"
        @click="pushNativelink(button.mplink)"
      >
        {{button.text}}
      </van-button>
    </van-empty>
  </div>
</template>

<script>
import SinglePicker from '@/components/form/singlePicker'
import { attachUpload, publishApi } from '@/api'
export default {
  components: {
    SinglePicker
  },

  data () {
    return {
      id: 0,
      tips: null,
      canPublish: true,
      categorys: [
        { name: '能源', id: 1 },
        { name: '计算机', id: 2 },
        { name: '生物科技', id: 3 },
        { name: '海洋', id: 4 },
        { name: '医疗健康', id: 5 },
        { name: '教育', id: 6 },
        { name: '金融', id: 7 }
      ],
      errorMessage: {
        title: '',
        category_id: '',
        content: ''
      },
      fieldOptions: {
        title: {
          error: false,
          errorMessage: '请输入需求的标题信息',
          required: true
        },
        category_id: {
          error: false,
          errorMessage: '请选择需求的分类',
          required: true
        },
        content: {
          error: false,
          errorMessage: '请输入需求的详细内容信息',
          required: true
        }
      },
      validateRules: [
        {
          name: 'category_id',
          required: true,
          error: false,
          errorMessage: '请输入'
        },
        {
          name: 'title',
          required: true,
          error: false,
          errorMessage: '请输入'
        },
        {
          name: 'content',
          required: true,
          error: false,
          errorMessage: '请输入'
        }
      ],
      imageList: [],
      attachs: [],
      textareaOption: {
        maxHeight: 150,
        minHeight: 100
      },
      formData: {
        title: '',
        category_id: '',
        content: '',
        images: [],
        attachs: []
      }
    }
  },
  onLoad (option) {
    this.id = option.id
    console.log(option)
    console.log('小程序 [page-blog] 生命周期: onLoad: 监听页面加载')
    this.tips = null
    this.imageList = []
    this.attachs = []
    this.formData = {
      title: '',
      category_id: '',
      content: '',
      images: [],
      attachs: []
    }
  },
  onHide () {
    console.log('thispage hide')
  },
  // 跳转后页面
  mounted () {
    console.log(this.id)
  },
  watch: {
    imageList: {
      handler (now, old) {
        let arrnew = now.map(obj => {
          return obj.path
        })
        this.formData.images = arrnew
      },
      deep: true,
      immediate: true
    },
    attachs: {
      handler (now, old) {
        this.formData.attachs = now.filter((item) => {
          return item.status === 'success'
        })
        console.log(now, this.formData.attachs)
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    console.log('PUBLISH created')
  },
  methods: {
    onBeforeRead (e) {
      const { file, callback } = e.mp.detail
      console.log(file)
      if (file.type === 'image') {
        const isImage = true
        callback(isImage)
      } else {
        const isImage = false
        console.log(callback)
        callback(isImage)
      }
    },
    onDeleteImage (e) {
      console.log(e)
      const { index } = e.mp.detail
      this.imageList.splice(index, 1)
    },
    onDeleteAttach (e) {
      console.log(e)
      const { index } = e.mp.detail
      this.attachs.splice(index, 1)
    },
    onAfterReadFiles (e) {
      const { file, name } = e.mp.detail
      console.log(name)
      console.log(file)
      const fileList = this.imageList
      if (Array.isArray(file)) {
        for (let i = 0; i < file.length; i++) {
          this.onUpload(file[i], this.imageList)
        }
      } else {
        this.onUpload(file, fileList)
      }
      console.log('upload res:', this.imageList)
    },
    onAfterRead (e) {
      const { file, name } = e.mp.detail
      console.log('onAfterRead name:', name)
      console.log('onAfterRead file:', file)
      this.onUpload(file, this.attachs, 'file')
    },
    onUpload (file, list, type = 'image') {
      console.log('onUpload>>>>>>>>>', file)
      return attachUpload(file, type).then(res => {
        list.push({
          ...file,
          status: 'success',
          url: res.url,
          path: res.path
        })
      }).catch(e => {
        console.log(e)
        list.push({
          ...file,
          status: 'failed',
          message: '上传失败'
        })
      })
    },
    onChangeInput (e) {
      const key = e.mp.target.id
      if (Object.prototype.hasOwnProperty.call(this.formData, key)) {
        this.formData[key] = e.mp.detail
      }
    },
    onCheckedCategory (data) {
      console.log('选择的分类', data)
      this.formData.category_id = data
    },
    validateAttributes () {
      let hasError = false
      const data = this.formData
      let options = this.fieldOptions
      for (let attribute in data) {
        if (Object.prototype.hasOwnProperty.call(options, attribute)) {
          let fieldRule = options[attribute]
          if (this.validateAttribute(fieldRule, attribute)) {
            fieldRule.error = false
            fieldRule.errorMessage = ''
            this.errorMessage[attribute] = ''
          } else {
            fieldRule.error = true
            this.errorMessage[attribute] = fieldRule.errorMessage
            hasError = true
          }
        }
      }
      return !hasError
    },
    validateAttribute (rule, name) {
      const attributeData = this.formData[name]
      if (rule.required && !attributeData) {
        return false
      }
      return true
    },
    onSubmit () {
      if (!this.validateAttributes()) {
        return
      }
      // console.log(this.formData)
      publishApi(this.formData).then(res => {
        console.log(res)
        this.tips = res
      }).catch(e => {
        console.log(e)
        this.tips = {
          description: '需求发布失败',
          image: '/static/images/blank/fail.png',
          buttons: [
            {
              type: 'default',
              text: '关闭',
              mplink: {
                type: 'back',
                route: 1
              }
            }
          ]
        }
      })
    }
  }
}
</script>

<style lang="less">
.container {
  background: #f4f5f9;
  padding-top: 10px;
  .van-cell {
    &-group {
      margin-bottom: 10px;
      background: #fff;
      &__title {
        padding: 20px 15px 10px !important;
      }
    }
  }
  .textarea-cell {
    .van-cell {
      flex-direction: column;
      &__value {
        margin-top: 10px;
      }
    }
    &__input {
      white-space: nowrap;
    }
  }
}
.images-upload {
  padding: 10px 15px;
}
.form-action {
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  .van-button {
    padding: 0 20px;
    min-width: 200px;
    height: 40px !important;
  }
}

.file-upload {
  .van-uploader {
    &__file-icon {
      font-size: inherit !important;
    }
    &__preview {
      &-delete,
      &-delete:after {
        position: initial !important;
      }
      &-image {
        height: 24px !important;
      }
    }
  }
  .uploader-index {
    &--van-uploader {
      display: flex;
      justify-content: flex-end;

      &__mask {
        flex-direction: row;
        background: #fff;
        color: #ff6600;
        &-icon {
          font-size: inherit;
        }
        &-message {
          margin: 0;
          padding: 0 3px;
        }
      }
      &__file {
        width: auto !important;
        height: auto !important;
        max-width: 95%;
        flex-direction: row;
        background: transparent;
        &-name {
          margin: 0;
        }
      }

      &__wrapper {
        max-width: 100%;
      }
      &__preview {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin: 0;
        max-width: 100%;
        &-delete {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0;
          &::after {
            display: none;
          }
          &-icon {
            display: initial;
            top: auto;
            right: auto;
            color: #000;
            transform: none;
          }
        }
      }
    }
  }
}
.van-empty__bottom {
  display: flex;
  align-items: center;
  justify-content: center;
  .van-button {
    margin: 0 5px;
  }
}
</style>
